<template>
  <HeaderFooterLayout>
    <view class="mx-5 pb-10">
      <u-form :rules="rules" :model="expiry" ref="formRef" labelWidth="80" labelPosition="left">
        <view v-if="editMode==='add'">
          <u-form-item v-if="editMode==='add'" required label="条形码" prop="barcode" borderBottom>
            <u-input type="number" @change="handleBarcodeInput" placeholder="必填" v-model="expiry.barcode" border="none"></u-input>
            <template #right>
              <u-icon @click="handleScan" name="scan" size="25"></u-icon>
            </template>
          </u-form-item>
          <u-form-item required label="名称" prop="name" borderBottom>
            <u-input placeholder="必填" v-model="expiry.name" border="none"></u-input>
          </u-form-item>
        </view>
        <view v-else>
          <u-form-item label="条形码" prop="barcode" borderBottom>
            {{ expiry.barcode }}
          </u-form-item>
          <u-form-item label="名称" prop="name" borderBottom>
            {{ expiry.name }}
          </u-form-item>
        </view>
        <u-form-item required label="生产日期" borderBottom>
          <DatePicker v-model:value="expiry.productionDate"></DatePicker>
        </u-form-item>

        <u-form-item required label="保质期/天" prop="shelfLife" borderBottom>
          <u-input type="number" placeholder="选填" v-model="expiry.shelfLife" border="none"></u-input>
        </u-form-item>
        <u-form-item label="预警天数" prop="notificationDays" borderBottom>
          <u-input type="number" placeholder="选填" v-model="expiry.notificationDays" border="none"></u-input>
        </u-form-item>
      </u-form>

    </view>
    <template #footer>
      <u-button type="primary" @click="handleSubmit">提交</u-button>
      <u-button v-if="editMode==='update'" type="error" :plain="true" @click="handleRemove">删除</u-button>
    </template>
  </HeaderFooterLayout>
</template>

<script setup lang="ts">

import {useProductStore} from "@/store/product";
import {storeToRefs} from "pinia";
import {onMounted, ref} from "vue";
import CategoryRadio from "@/pages/product/product/components/CategoryRadio.vue";
import SupplierRadio from "@/pages/product/product/components/SupplierRadio.vue";
import DatePicker from "@/pages/product/product/components/DatePicker.vue";
import HeaderFooterLayout from "@/layout/HeaderFooterLayout.vue";
import {debounce} from "@/utils";
import api from "@/api";
import MyDayjs from "@/utils/common/myDayjs";

const formRef = ref()
const productStore = useProductStore()
const {selectedExpiry, editMode} = storeToRefs(productStore)
const expiry = ref(<IExpiry>{
  name: ''
})
const rules = ref({
  barcode: [
    {
      required: true,
      message: '请输入条形码',
      trigger: ['blur', 'change']
    },
    {
      required: true,
      message: '请输入有效条形码',
      type: 'pattern',
      pattern: '^69[0-9]{11}$',
      trigger: ['blur', 'change']
    }
  ],
  name: [
    {
      required: true,
      message: '请输入名称',
      trigger: ['blur', 'change']
    },
    {
      required: true,
      type: 'pattern',
      pattern: '^.{3,20}$',
      message: '请输入长度为2-20的名称',
      trigger: ['blur', 'change']
    }
  ],
  price: [
    {
      required: true,
      message: '请输入零售价',
      trigger: ['blur', 'change']
    },
    {
      required: true,
      type: 'pattern',
      pattern: '^[1-9][0-9]*$',
      message: '请输入有效数字',
      trigger: ['blur', 'change']
    },
  ],
  stockQuantity: [
    {
      type: 'integer',
      message: '请输入整数',
      trigger: ['blur', 'change']
    }
  ],
  shelfLife: [
    {
      type: 'integer',
      message: '请输入整数',
      trigger: ['blur', 'change']
    }
  ],
  notificationDays: [
    {
      type: 'integer',
      message: '请输入整数',
      trigger: ['blur', 'change']
    }
  ]
})


onMounted(() => {
  if (editMode.value === 'update') {
    uni.setNavigationBarTitle({
      title: '编辑保质期'
    })
  } else if (editMode.value === 'add') {
    uni.setNavigationBarTitle({
      title: '新增保质期'
    })
    handleScan()
  }
  expiry.value = JSON.parse(JSON.stringify(selectedExpiry.value))
})
const handlePreAdd = debounce(() => {
  uni.showLoading({
    title: '加载中'
  })
  api.expiry.preAdd({
    barcode: expiry.value.barcode
  }).then((re: any) => {
    if (re.data.code === 0) {
      if (re.data.msg === "已存在") {
        uni.showModal({
          title: '提示',
          content: '该商品已有保质期管理，是否继续添加',
          success: function (r) {
            if (r.confirm) {
              expiry.value = re.data.data
            } else if (r.cancel) {
              expiry.value.barcode = ''
            }
          }
        })
      } else if (re.data.msg === '大数据为空') {
      } else {
        expiry.value = re.data.data
      }
    }
  }).finally(() => {
    uni.hideLoading()
  })

}, 1000)

const handleScan = () => {
  uni.scanCode({
    success: function (res) {
      console.log(res)
      expiry.value.barcode = res.result
      if (res) {
        handlePreAdd()
      }
    }
  });
}
const handleBarcodeInput = (value: any) => {
  const pattern = /^69[0-9]{11}$/;
  if (pattern.test(value)) {
    handlePreAdd()
  }

}

const handleSubmit = () => {
  formRef.value.validate().then((res: any) => {
    if (res) {
      if (editMode.value === 'update') {
        api.expiry.update(expiry.value).then((res: any) => {
          if (res.data.code === 0) {
            expiry.value = res.data.data
            productStore.updateExpiry(expiry.value)
            uni.navigateBack({
              success() {
                uni.showToast({
                  title: '修改成功',
                  icon: 'success'
                })
              }
            })
          }
        })
      } else if (editMode.value === 'add') {
        api.expiry.add(expiry.value).then((res: any) => {
              if (res.data.code === 0) {
                expiry.value = res.data.data
                productStore.unshiftExpiry(expiry.value)
                uni.navigateBack({
                  success() {
                    uni.showToast({
                      title: '添加成功',
                      icon: 'success'
                    })
                  }
                })
              }
            }
        )
      }
    }
  })
}

const handleRemove = () => {
  uni.showModal({
    title: '提示',
    content: '确定删除吗？',
    success: function (res) {
      if (res.confirm) {
        api.expiry.removeById({
          id: expiry.value.id
        }).then((res: any) => {
          if (res.data.code === 0) {
            productStore.removeExpiry(expiry.value)
            uni.navigateBack({
              success() {
                uni.showToast({
                  title: '删除成功',
                  icon: 'success'
                })
              }
            })
          }
        })

      } else if (res.cancel) {
        console.log('用户点击取消');
      }
    }
  })
}

</script>


<style scoped>

</style>